package com.airhockey;

import com.airhockey.R;

import Jeu.Jeu;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * A GraphicView is a SurfaceView that draw constantly the game on the screen
 * and catch all the movement of the player
 * @author Maxime
 */

public class GraphicView extends SurfaceView implements SurfaceHolder.Callback{

	/* Sufrace Holder */
	private SurfaceHolder surfaceHolder = null;
	/* Thread d'affichage */
	DrawingThread drawingThread;
	/* Dimension client */
	int width;
	int height;
	/* Painter */
	Paint mPaint;
	/* Fond */
	Bitmap background;
	
	/* Graphic Object = les pusher et le palet */
	GraphicObject pusher;
	GraphicObject pusher2;
	GraphicObject palet;
	
	/* Dimension objets client */
	int radiusPaletW=0;
	int radiusPaletH=0;
	int radiusPusherW=0;
	int radiusPusherH=0;
	int radiusGoal=0;
	
	/* Objet visibe ou non */
	boolean graphicObjectsvisible=false;
	/* Attraper la cross */
	boolean holding=false;

	GameActivity activity;
	
	/* Temps */
	long time = System.currentTimeMillis();
	
	
	public GraphicView(Context context) {
		super(context);

		//On récupère le Holder
		surfaceHolder = getHolder();

		surfaceHolder.addCallback(this);
		
		//objet graphiques
		pusher = new GraphicObject();
		pusher2 = new GraphicObject();
		palet = new GraphicObject();
		
		mPaint = new Paint();		
		activity = (GameActivity)context;		
	}

	@Override
	public boolean onTouchEvent(MotionEvent e) {
	  
		int index = e.getActionIndex();
		int id = e.getPointerId(index);
		long elapsed = System.currentTimeMillis() - time;

		//on limite les mis à jour toute les 20 milisecondes (évite de surcharger le serveur)
		if(elapsed>50)
		{
			time= System.currentTimeMillis();

			if(e.getAction() == android.view.MotionEvent.ACTION_DOWN && id==0)
			{
				if(!holding)
				{
					Rect rect = new Rect(pusher.getX()-radiusPaletW, pusher.getY()-radiusPaletH, pusher.getX()+radiusPaletW, pusher.getY()+radiusPaletH);

					if(rect.contains((int)e.getX(),(int) e.getY()))
					{
						activity.SendPusherPosition((int)e.getX(), (int)e.getY());
						holding=true;
					}
				}
			}
			else if(e.getAction() == android.view.MotionEvent.ACTION_MOVE && id==0)
			{
				if(holding)			
				{
					activity.SendPusherPosition((int)e.getX(), (int)e.getY());
				}
			}
			else if(e.getAction() == android.view.MotionEvent.ACTION_UP)
			{
				holding=false;
			}
		}
		return true;
	}
	

	@Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}

	@Override
	public void onDraw(Canvas canvas)
	{
		canvas.drawColor(Color.WHITE);
		/* fond */
		canvas.drawBitmap(background, 0,0, mPaint);

		mPaint.setColor(Color.GRAY);
		mPaint.setStrokeWidth(5);
		mPaint.setStyle(Paint.Style.STROKE);

		/* ligne et cercle du milieu */
		int radiusCenter = width/6;
		canvas.drawLine(0, height/2, (width/2)-radiusCenter, height/2, mPaint);
		canvas.drawLine((width/2)+radiusCenter, height/2, width, height/2, mPaint);
		canvas.drawCircle(width/2, height/2, radiusCenter, mPaint);

		/* buts */
		mPaint.setColor(Color.BLUE);
		canvas.drawCircle((width/2), height, radiusGoal, mPaint);
		mPaint.setColor(Color.RED);
		canvas.drawCircle((width/2), 0, radiusGoal, mPaint);

		/* objets graphiques (cross+palet)*/
		
		if(graphicObjectsvisible)
		{
			canvas.drawBitmap(pusher.image, pusher.getX()-(pusher.image.getWidth()/2),pusher.getY()-(pusher.image.getHeight()/2), mPaint);
			canvas.drawBitmap(pusher2.image,pusher2.getX()-(pusher2.image.getWidth()/2),pusher2.getY()-(pusher2.image.getHeight()/2), mPaint);
			canvas.drawBitmap(palet.image, palet.getX()-(palet.image.getWidth()/2),palet.getY()-(palet.image.getHeight()/2), mPaint);
		}

	}

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
    	
    	if (drawingThread==null || (drawingThread!=null && !drawingThread.running)) 
    		drawingThread = new DrawingThread();
        
    	drawingThread.setRunning(true); 	
    	Canvas canvas = null;
    	
        try {
        	
            canvas = holder.lockCanvas(null);
      
            this.width = canvas.getWidth();
            this.height = canvas.getHeight();
            
            /* chargement du fond */
            Bitmap back = BitmapFactory.decodeResource(getResources(), R.drawable.background);
    	    background = Bitmap.createScaledBitmap(back, width, height, true);
    	    
    	    /* chargement des tailles des objets */
    		radiusPaletW = activity.gestionPartie.getRatioPoint((int)Jeu.taillePalet,Jeu.taillePlateau[0],width);
    		radiusPaletH = activity.gestionPartie.getRatioPoint((int)Jeu.taillePalet,Jeu.taillePlateau[1],height);
    		radiusPusherW = activity.gestionPartie.getRatioPoint((int)Jeu.tailleJoueur,Jeu.taillePlateau[0],width);
    		radiusPusherH = activity.gestionPartie.getRatioPoint((int)Jeu.tailleJoueur,Jeu.taillePlateau[1],height);
        	radiusGoal = activity.gestionPartie.getRatioPoint((int)Jeu.tailleBut/2,Jeu.taillePlateau[0],width);
        	
        	/*affectation des images aux objets */
        	pusher.setImage(this, radiusPusherW*2,radiusPusherH*2,R.drawable.player );
     	    pusher2.setImage(this, radiusPusherW*2,radiusPusherH*2,R.drawable.playerdeux );
     	    palet.setImage(this, radiusPaletW*2,radiusPaletH*2,R.drawable.ball );
  
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (canvas != null) {
                holder.unlockCanvasAndPost(canvas);
            }
        }
        /* lancement du thread */
        drawingThread.start();
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        
    	 drawingThread.setRunning(false);
         boolean retry = true;
         while (retry) {
             try {
            	 /* on attend que le thread se termine */
                 drawingThread.join();
                 retry = false;
             } catch (InterruptedException e) {}
         }
    }
    
    /**
     * The drawing thread constantly update the surfaceView
     * @author Maxime
     */
	private class DrawingThread extends Thread {
        boolean running = true;
        
        public void setRunning(Boolean b)
        {
        	running=b;
        }
        
        @SuppressLint("WrongCall")
		@Override
        public void run() {
        	Canvas canvas;

        	while (running) {
        		canvas = null;
        		try {
        			canvas = surfaceHolder.lockCanvas();
        			synchronized (surfaceHolder) 
        			{
        				if(canvas != null)
        					onDraw(canvas);
        			}
        		} finally {
        			if (canvas != null)
        				surfaceHolder.unlockCanvasAndPost(canvas);
        		}
        	}
        }
	}

}
